<template>
  <!--博文列表-->
  <el-row :gutter="12">
    <el-col :span="5">
      <!--分组-->
      <blogGroup :isEdit="false"/>
    </el-col>
    <el-col :span="18">
      <el-card shadow="hover"
        v-for="(item, index) in dataList"
        :key="'bloglist_' + index"
      >
        <template #header>
          <div class="card-header">
            <router-link :to="{name:'blogs', params:{id:item.ID}}">
              {{item.title}}
            </router-link>
            <span class="button">({{dateFormat(item.addTime).format('YYYY-MM-DD')}})</span>
          </div>
        </template>
        <!--简介-->
        <div class="text item" v-html="item.introduction"></div>
        <hr>
        <i class="el-icon-view"></i>&nbsp;{{item.viewCount}}&nbsp;&nbsp;
        <i class="el-icon-circle-check"></i>&nbsp;{{item.agreeCount}}&nbsp;&nbsp;
        <i class="el-icon-chat-dot-square"></i>&nbsp;{{item.discussCount}}&nbsp;
      </el-card>
      <!--没有找到数据-->
      <el-empty description="没有找到博文呢。" v-if="dataList.length === 0"></el-empty>
      <pager/>
    </el-col>
  </el-row>
</template>

<script setup>
import { defineProps, watch } from 'vue'
// 路由，监听 params （props） 的变化
import { useRoute, onBeforeRouteUpdate } from 'vue-router'
// 组件
import blogGroup from '../components/blog-group.vue'
import pager from '../components/pager.vue'

// 数据列表的状态
import dataListControl from '../control/data-list'

// 属性，接收路由的分组ID
const props = defineProps({
  groupId: Number
})
// 日期格式化
const dateFormat = dayjs
// 获取操作函数：注入状态，博文列表数组，
const { regDataListState, dataList } = dataListControl('homeBlog')

// 注册状态，注入获取博文列表需要 查询条件 和 分页信息
const blogState = regDataListState()

// url直接进入的时候有效。判断是首页路由进入，还是分组路由进入
if (typeof props.groupId === 'undefined') {
  // 首页，分组ID设置为 0， 显示所有已发布的博文列表
  blogState.find.groupId = 0
  blogState.find.title = ''
  blogState.isReload = !blogState.isReload
} else {
  // 按照分组ID显示博文列表
  blogState.find.groupId = props.groupId
  blogState.find.title = ''
  blogState.isReload = !blogState.isReload
}

// 根据路由 params 的变化，设置分组ID
onBeforeRouteUpdate((to, from, next) => {
  // blogState.find.groupId = to.params.groupId
  // blogState.find.title = ''
  // blogState.isReload = !blogState.isReload
  next()
})

const route = useRoute()
// 监听路由变化
watch(() => route.fullPath, () => {
  if (route.fullPath === '/' || route.fullPath === '/vue3-blog') {
    blogState.find.groupId = 0
    blogState.find.title = ''
    blogState.isReload = !blogState.isReload
  } else {
    blogState.find.groupId = route.params.groupId
    blogState.find.title = ''
    blogState.isReload = !blogState.isReload
  }
})

</script>

<style>
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }
</style>
